package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.DateUtil;
import com.dc.common.ResponseResultVO;
import com.dc.entity.FireWorkOrder;
import com.dc.entity.WorkOrder;
import com.dc.entity.ro.FireWorkOrderRO;
import com.dc.entity.vo.FireVO;
import com.dc.enums.OrderType;
import com.dc.enums.OrderTypeEng;
import com.dc.enums.WebSocketMessage;
import com.dc.feign.SystemApiServiceFeign;
import com.dc.mapper.FireWorkOrderMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.service.FireWorkOrderService;
import com.dc.util.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.beans.BeanCopier;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
@Slf4j
public class FireWorkOrderServiceImpl extends ServiceImpl<FireWorkOrderMapper, FireWorkOrder> implements FireWorkOrderService {

    @Resource
    private WorkOrderMapper workOrderMapper;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 系统模块
     */
    @Resource
    private SystemApiServiceFeign systemApiServiceFeign;

    // TODO 对接设备之后，设备报警生成工单接口,参数待定
    @Override
    public ResponseResultVO automaticFireWorkOrder() {
        WorkOrder fireWorkOrder = new WorkOrder();
        fireWorkOrder.setId(SnowflakeIdWorker.generateId());
        fireWorkOrder.setNumber(redisUtil.serialNumber("HJCZ"));
        fireWorkOrder.setRepairType(0);
        int i = workOrderMapper.insert(fireWorkOrder);
        //工单数量加入缓存
        if (i > 0) {
            if (!CommonCodeUtil.increasing(OrderTypeEng.FIRE.getName())) {
                //如果缓存为空，则查数据库再插入到redis
                Integer integer = workOrderMapper.selectCount(new QueryWrapper<WorkOrder>().lambda().eq(WorkOrder::getType, OrderType.FIRE.getId()));
                redisUtil.set(OrderTypeEng.FIRE.getName(), 0 == integer ? 1 : integer);
            }
        }
        return ResponseResultVO.insertResult(i);
    }

    @Override
    public ResponseResultVO insertFireWorkOrder(FireWorkOrderRO ro) {
        WorkOrder workOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, workOrder);
        workOrder.setId(SnowflakeIdWorker.generateId());
        workOrder.setNumber(redisUtil.serialNumber("HJCZ"));
        workOrder.setUserId(Long.valueOf(UserUtil.getUserId()));
        workOrder.setUserName(String.valueOf(redisUtil.get(UserUtil.getUserId())));
        workOrder.setRecTime(DateUtil.parseStrToDate(ro.getRecTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        workOrder.setAlarmTime(DateUtil.parseStrToDate(ro.getAlarmTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        workOrder.setType(OrderType.FIRE.getId());
        int i = workOrderMapper.insert(workOrder);
        if (i > 0) {
            if (!CommonCodeUtil.increasing(OrderTypeEng.FIRE.getName())) {
                //如果缓存为空，则查数据库再插入到redis
                Integer integer = workOrderMapper.selectCount(new QueryWrapper<WorkOrder>().lambda().eq(WorkOrder::getType, OrderType.FIRE.getId()));
                redisUtil.set(OrderTypeEng.FIRE.getName(), 0 == integer ? 1 : integer);
            }
            // 发送消息到通知人
            String message = String.format("工单%s已接警,请及时处理!", workOrder.getNumber());
            systemApiServiceFeign.sendWebsocketMessage(String.format(WebSocketMessage.OTHER_MESSAGE.getContent(), message),
                    Arrays.asList(String.valueOf(ro.getLeaderUserId())));
        }
        return ResponseResultVO.insertResult(i);
    }

    @Override
    public ResponseResultVO updateFireWorkOrder(FireWorkOrderRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WorkOrder fireWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, fireWorkOrder);
        return ResponseResultVO.updateResult(workOrderMapper.updateById(fireWorkOrder));
    }

    @Override
    public ResponseResultVO deleteFireWorkOrder(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        int deleteBatchIds = workOrderMapper.deleteBatchIds(idList);
        if (deleteBatchIds > 0) {
            redisUtil.diminishing(OrderTypeEng.FIRE.getName(), deleteBatchIds);
        }
        return ResponseResultVO.deleteResult(deleteBatchIds);
    }

    @Override
    public ResponseResultVO selectFireWorkOrderList(FireWorkOrderRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        //条件构造
        //是否是H5
        if (StringUtils.isNotBlank(ro.getClient()) && "H5".equalsIgnoreCase(ro.getClient())) {
            queryWrapper.lambda().eq(WorkOrder::getReportUserId, UserUtil.getUserId());
        }
        queryWrapper.lambda().eq(WorkOrder::getType, OrderType.FIRE.getId());
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(ro.getIds()), WorkOrder::getId, ro.getIds());
        queryWrapper.orderBy(StringUtils.isNotBlank(ro.getOrderByColumn()), "asc".equalsIgnoreCase(ro.getIsAsc()) ? true : false, StringUtils.toLine(ro.getOrderByColumn()));
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getNumber()), WorkOrder::getNumber, ro.getNumber());
        queryWrapper.lambda().eq(null != ro.getReportUserId(), WorkOrder::getReportUserId, ro.getReportUserId());
        queryWrapper.lambda().eq(null != ro.getStatus(), WorkOrder::getStatus, ro.getStatus());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getSerialNumber()), WorkOrder::getSerialNumber, ro.getSerialNumber());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getRegionName()), WorkOrder::getRegionName, ro.getRegionName());
        //上报时间区间查询
        queryWrapper.apply(StrUtil.isNotBlank(ro.getCreateTime()),
                "date_format (create_time,'%Y-%m-%d') >= date_format('" + ro.getCreateTime() + "','%Y-%m-%d')");
        queryWrapper.apply(StrUtil.isNotBlank(ro.getCreateEndTime()),
                "date_format (create_time,'%Y-%m-%d') < date_format('" + ro.getCreateEndTime() + "','%Y-%m-%d')");
        //接警时间区间查询
        queryWrapper.apply(StrUtil.isNotBlank(ro.getAlarmTime()),
                "date_format (alarm_time,'%Y-%m-%d') >= date_format('" + ro.getAlarmTime() + "','%Y-%m-%d')");
        queryWrapper.apply(StrUtil.isNotBlank(ro.getAlarmEndTime()),
                "date_format (alarm_time,'%Y-%m-%d') < date_format('" + ro.getAlarmEndTime() + "','%Y-%m-%d')");
        queryWrapper.lambda().orderByDesc(WorkOrder::getCreateTime);
        Page<WorkOrder> orderPage = workOrderMapper.selectPage(page, queryWrapper);
        List<FireVO> fireVOS = orderPage.getRecords().stream().map(e -> {
            FireVO d = new FireVO();
            final BeanCopier copier = BeanCopier.create(WorkOrder.class, FireVO.class, false);
            copier.copy(e, d, null);
            return d;
        }).collect(Collectors.toList());
        ro.setTotalCount(workOrderMapper.selectCount(queryWrapper));
        return ResponseResultVO.resultPageList(fireVOS, ro);

    }

    @Override
    public void fireWorkOrderRecordExport(HttpServletResponse response, FireWorkOrderRO ro) {
        ResponseResultVO roadReportForm = this.selectFireWorkOrderList(ro);
        HashMap<String, Object> data = (HashMap<String, Object>) roadReportForm.getData();
        ExportUtil.exportExcelNew("火警处置记录", (List) data.get("list"), FireVO.class, response);
    }
}
